<?php
namespace App\Wen\Utils;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Http\Controllers\Api\Repositories\WxContRepositories;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Jobs\SubscribeMessageJob;
use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsWeightRefresh;
use App\Models\Shop\WxShopOrder;
use App\Models\Shop\WxShopOrderGoods;
use App\Models\User\WxUser;
use App\Models\User\WxUserContactApply;
use App\Models\User\WxUserInviteBenefitRecord;
use App\Models\WxDomainAuth;
use App\Models\WxExceptional;
use App\Models\WxOrder;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class OrderUtils{
    /**
     * 充电
     * @param $order
     */
    public static function exceptional($order)
    {
        $data = unserialize($order['parame']);

        // 增加充电记录
        (new WxExceptional())->addExceptional($order['user_id'], $data['postsId'], $data['postsUserId'], $order['order_pay_price']);
        $user_name = WxUser::where('id', $order['user_id'])->value('user_name');
        $platform_percent = _between_(Settings::get('app_reward_platform_percent', 50), 0, 100);
        $platform_percent_ = round(( $platform_percent / 100 ) * $order['order_pay_price'], 2);
        $user_percent_ = round($order['order_pay_price'] - $platform_percent_, 2);

        if($platform_percent_ > 0){
            // 给作者增加余额
            UserUtils::update_user_financial($data['postsUserId'], 0,
                $user_percent_,
                '您收到了一笔来自「' . $user_name . '(id:'. $order['user_id'] .')」的充电，充电金额¥' . $order['order_pay_price'] . '，其中系统分成'.$platform_percent.'%',
                $data['postsId']
            );
        }else{
            // 给作者增加余额
            UserUtils::update_user_financial($data['postsUserId'], 0,
                $order['order_pay_price'],
                '您收到了一笔来自「' . $user_name . '(id:'. $order['user_id'] .')」的充电，充电金额¥' . $order['order_pay_price'],
                $data['postsId']
            );
        }

        SubscribeMessageJob::dispatch('exceptional', $order->id);

        Cache::forget('post:exceptional:list:'.$data['postsId']);
        Cache::forget('exceptional:cont:'.$data['postsId']);
    }

    /**
     * 处理普通订单的所得，但不处理订单的状态，不可重复调用
     * @param WxOrder $WxOrder
     * @param $which_pay
     * @return false
     */
    public static function order_obtains(WxOrder &$WxOrder, $which_pay = -1){
        $type = $WxOrder->order_type;
        $uid = $WxOrder->user_id;
        $order_price = $WxOrder->order_price;
        // 开会员
        if ($type == 1) {
            $vip_options = json_decode(Settings::get('app_vip_options', '[]'), true);
            if(_empty_($vip_options)){
                return false;
            }
            $flag = false;
            $days = 0;
            $coins = 0;
            foreach ($vip_options as $option){
                if($option && $option['price'] == $order_price){
                    $flag = true;
                    $days = $option['days'];
                    $coins = $option['coins'];
                    break;
                }
            }
            if($flag){
                WxUserRepositores::vip($uid, $days);
                if($coins > 0){
                    UserUtils::update_user_coins($uid, 13, $coins, '开通'.$days.'天会员，赠送'.$coins. Settings::get('app_coin_name', '硬币'));
                }
            }
        }else if ($type == 2) {
            self::exceptional($WxOrder);
        }else if ($type == 3) {

            $recharge_list_arr = Settings::get('app_balance_recharge_list', []);
            if($recharge_list_arr){
                foreach ($recharge_list_arr as $option){
                    if($option['rmb'] == $order_price){
                        UserUtils::update_user_financial($uid, 6, $option['balance'], '充值了'.$option['balance'].'余额');
                        break;
                    }
                }
            }
        }else if ($type == 6) {
            $parame = unserialize($WxOrder->parame);
            if(_array_key($parame, 'post_id', 0) > 0 && _array_key($parame, 'hour', 0) > 0){
                $the_post = WxPost::where('id', $parame['post_id'])->first();
                $the_weight = $the_post->weight;
                if($the_weight < time()){
                    $the_weight = time();
                }
                $the_weight += $parame['hour'] * 3600;

                WxPost::withoutSyncingToSearch(function () use ($the_weight, &$parame) {
                    WxPost::where('id', $parame['post_id'])->update(['weight'=>timetostr($the_weight)]);
                });
            }else if(_array_key($parame, 'post_id', 0) > 0 && _array_key($parame, 'time_list', '')){
                $time_list = json_decode(_array_key($parame, 'time_list', ''), true);
                if($time_list){
                    $insert_data = [];
                    sort($time_list);
                    $post_refresh_cost = floor(($WxOrder->order_pay_price / count($time_list)) * 100) / 100;
                    foreach ($time_list as $timestap){
                        $insert_data[] = [
                            'user_id' => $WxOrder->user_id,
                            'post_id' => $parame['post_id'],
                            'expect_time' => Carbon::createFromTimestamp((int)($timestap / 1000)),
                            'refresh_time' => null,
                            'balance_cost' => $post_refresh_cost,
                            'status' => 0
                        ];
                    }
                    WxPostsWeightRefresh::insert($insert_data);
                }
            }
        }else if ($type == 7) {
            if(!_empty_($WxOrder->parame)){
                $parame = unserialize($WxOrder->parame);
                if(_array_key($parame, 'circle_id', 0) > 0){
                    $circle = WxCircle::find($parame['circle_id']);
                    $platform_division = _between_(Settings::get('app_circle_follow_pay_division', 0), 0, 100);
                    $platform_reward = round($platform_division * $WxOrder->order_pay_price / 100, 2);
                    $circle_user_reward = round($WxOrder->order_pay_price - $platform_reward, 2);
                    $r = WxCircleRepositores::userFollowCircle($uid, $circle->id, Carbon::now()->addDays((int)$circle->follow_pay_duration)->toDateTimeString());
                    if($r){
                        if($circle_user_reward >= 0.01){
                            $pay_res_ = UserUtils::update_user_financial($circle->user_id, 23, $circle_user_reward, '有新的用户(id: '.$uid.')加入您的付费圈子，扣掉平台分成'.$platform_division.'%，您获得'.$circle_user_reward.'余额。');
                        }
                    }
                }
            }

        }else if ($type == 8) {
            if($which_pay === 0){
                $title = '微信充值';
            }else if($which_pay === 1){
                $title = '支付宝充值';
            }else if($which_pay === 2){
                $title = '支付充值';
            }else if($which_pay === 3){
                $title = '苹果支付充值';
            }
            UserUtils::update_user_shop_gurantee($uid, $order_price, $title);
            Cache::forget('get:cached:user:'.$uid);
        }else if($type == 9){
            $parame = unserialize($WxOrder->parame);
            if(_empty_(_array_key($parame, 'domain', ''))){
                $domain_auth = WxDomainAuth::where('user_id', $uid)->first();
            }else{
                $domain = _array_key($parame, 'domain', '');
                $domain_auth = WxDomainAuth::where('domain_1', $domain)->orWhere('domain_2', $domain)
                    ->orWhere('domain_3', $domain)->orWhere('domain_4', $domain)
                    ->orWhere('domain_5', $domain)->orWhere('domain_6', $domain)
                    ->orWhere('domain_7', $domain)->first();
            }

            if($domain_auth){
                $base_pays = explode(',', $domain_auth->pays);
                $base_pays[] = $parame['num'];
                $base_pays = array_unique($base_pays);
                if($domain_auth){
                    WxDomainAuth::where('id', $domain_auth->id)->update(['pays' => implode(',', $base_pays)]);
                }

                if($parame['num'] == 0){
                    if($domain_auth && $domain_auth->user_id != $uid){
                        WxUser::where('id', $domain_auth->user_id)->update([
                            'who' => $uid
                        ]);
                    }
                }
            }else{
                if(_array_key($parame, 'user_id', 0) > 0){
                    // 新建授权
                    $model = new WxDomainAuth();
                    $model->user_id = $parame['user_id'];
                    $model->domain_1 = $parame['domain'];
                    $model->tenant_1 = '0,999';
                    $model->pays = $parame['num'];
                    $r = $model->save();

                    if($parame['num'] == 0){
                        if($parame['user_id'] != $uid){
                            WxUser::where('id', $model->user_id)->update([
                                'who' => $uid
                            ]);
                        }
                    }
                }
            }

        }else if($type == 10){
            $parame = unserialize($WxOrder->parame);
            if(!_empty_(_array_key($parame, 'user_id', '')) && !_empty_(_array_key($parame, 'user_state', 0))){
                $the_user = WxUser::find($parame['user_id']);
                if($the_user && $the_user->user_state == $parame['user_state']){
                    UserUtils::unlock_user($the_user, $the_user->user_state);
                    if($WxOrder->user_id != $parame['user_id']){
                        UserUtils::assistant_notice($parame['user_id'], '用户(<a href="/pages/user/user?id='.$WxOrder->user_id.'">'.UserUtils::get_cached_user_name($WxOrder->user_id).' id:'.$WxOrder->user_id.'</a>)花费了￥'.$WxOrder->order_pay_price.'帮您解除了账号的'.($the_user->user_state == 2 ? '封号' : '禁言').'限制');
                    }
                }
            }
        }else if($type == 11){
            $parame = unserialize($WxOrder->parame);
            if(!_empty_(_array_key($parame, 'object_id', ''))){
                $the_user = WxUser::find($parame['object_id']);
                if($the_user){
                    DB::beginTransaction();
                    try {
                        // todo:
                        $user_contact = WxUserContactApply::where('user_id', $WxOrder->user_id)->where('object_id', $the_user->id)->first();
                        $is_need_save = false;
                        $chat_content = '';
                        if($user_contact){
                            if($user_contact->status != 1){
                                WxUserContactApply::where('user_id', $WxOrder->user_id)->where('object_id', $the_user->id)->delete();
                                $user_contact = new WxUserContactApply();
                                $user_contact->user_id = $WxOrder->user_id;
                                $user_contact->object_id = $the_user->id;
                                $user_contact->status = 1;
                            }
                            if(!_empty_(_array_key($parame, 'is_wechat_account', ''))){
                                $user_contact->is_wechat_account = 1;
                                if(!_empty_($chat_content)){
                                    $chat_content .= '、';
                                }
                                $chat_content .= '微信号';
                                $is_need_save = true;
                            }
                            if(!_empty_(_array_key($parame, 'is_phone', ''))){
                                $user_contact->is_phone = 1;
                                if(!_empty_($chat_content)){
                                    $chat_content .= '、';
                                }
                                $chat_content .= '手机号';
                                $is_need_save = true;
                            }
                        }else{
                            $is_need_save = true;
                            $user_contact = new WxUserContactApply();
                            $user_contact->user_id = $WxOrder->user_id;
                            $user_contact->object_id = $the_user->id;
                            $user_contact->status = 1;

                            if(_array_key($parame, 'is_wechat_account', '') == 1){
                                $user_contact->is_wechat_account = 1;
                                if(!_empty_($chat_content)){
                                    $chat_content .= '、';
                                }
                                $chat_content .= '微信号';
                            }

                            if(_array_key($parame, 'is_phone', '') == 1){
                                $user_contact->is_phone = 1;
                                if(!_empty_($chat_content)){
                                    $chat_content .= '、';
                                }
                                $chat_content .= '手机号';
                            }
                        }

                        if($is_need_save){
                            $reason = _empty_default_(_array_key($parame, 'reason', ''), '');
                            if($reason){
                                $user_contact->reason = $reason;
                            }

                            $platform_percent = _between_(Settings::get('app_contact_pay_platform_percent', 10.0), 0, 100);
                            $pay_amount = round(($WxOrder->order_pay_price * ( 100 - $platform_percent )) / 100, 2);
                            if($pay_amount >= 0.01){
                                UserUtils::update_user_financial($the_user->id,31, $pay_amount, '用户(id:'.$WxOrder->user_id.')付费获取了你的'.$chat_content);
                            }
                            $chat_content = '我付费￥'.$WxOrder->order_pay_price.'获取了你的'.$chat_content. (!_empty_($reason) ? '，并留言：'.$reason : '');
                            $chatmodel = WxContRepositories::add($WxOrder->user_id, $the_user->id, $chat_content, '', '', 0, 0, 0, 0, 0);
                            if($chatmodel) {
                                $websocket_id = GatewayUtils::uid2client_id($the_user->id);
                                if ($websocket_id) {
                                    GatewayUtils::success($websocket_id, 5, ['chat_content' => _mini_emoji($chat_content, true), 'chat_image' => '',
                                        'from_user' => UserUtils::get_cached_user($WxOrder->user_id)]);
                                }
                            }
                            if($chatmodel){
                                $user_contact->chat_id = $chatmodel->id;
                            }
                            $r = $user_contact->save();
                        }
                        DB::commit();
                    } catch (\Exception $e) {
                        DB::rollBack();
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }
            }
        }
        self::userInviteBenefitProcess($WxOrder->id, 0);
    }

    public static function get_order_benefit_rate($type, $is_shop = false, $layer = 1){
        $order_rate = Settings::get($is_shop ? 'user_invite_benefit_shop_order_rate_'.$layer : 'user_invite_benefit_order_rate_'.$layer, []);
        if(_empty_($order_rate)){
            return [
                'lv1' => 0,
                'lv2' => 0,
                'lv3' => 0,
            ];
        }
        foreach ($order_rate as $order_){
            $flag = false;
            if($type === '0' || $type === 0){
                if($order_['type'] === '0' || $order_['type'] === 0){
                    $flag = true;
                }
            }else{
                if($order_['type'] == $type){
                    $flag = true;
                }
            }

            if($flag){
                return [
                    'lv1' => _array_key($order_, 'lv1', 0),
                    'lv2' => _array_key($order_, 'lv2', 0),
                    'lv3' => _array_key($order_, 'lv3', 0),
                ];
            }
        }
        return [
            'lv1' => 0,
            'lv2' => 0,
            'lv3' => 0,
        ];
    }


    public static function userInviteBenefitProcess($order_id, $shop_order_id){
        global $__MINI_GLOBAL_PAYCODE_20__;
        if(!$__MINI_GLOBAL_PAYCODE_20__){
            return;
        }

        if(Settings::get('user_invite_benefit_status') != 1){
            return;
        }
        $order = null;
        $benefit_rate_1 = ['lv1' => 0,'lv2' => 0,'lv3' => 0,];
        $benefit_rate_2 = ['lv1' => 0,'lv2' => 0,'lv3' => 0,];
        $benefit_rate_3 = ['lv1' => 0,'lv2' => 0,'lv3' => 0,];

        if($order_id > 0){
            $order = WxOrder::find($order_id);
            $benefit_rate_1 = self::get_order_benefit_rate($order->order_type);
            $benefit_rate_2 = self::get_order_benefit_rate($order->order_type, false, 2);
            $benefit_rate_3 = self::get_order_benefit_rate($order->order_type, false, 3);
        }else if($shop_order_id > 0){
            $order = WxShopOrder::find($shop_order_id);
            $benefit_rate_1 = self::get_order_benefit_rate($order->order_from, true);
            $benefit_rate_2 = self::get_order_benefit_rate($order->order_from, true, 2);
            $benefit_rate_3 = self::get_order_benefit_rate($order->order_from, true, 3);
        }
        $lv1_rate = _between_($benefit_rate_1['lv1'], 0, 100);
        $lv2_rate = _between_($benefit_rate_1['lv2'], 0, 100);
        $lv3_rate = _between_($benefit_rate_1['lv3'], 0, 100);

//        $lv1_rate = _between_(Settings::get('user_invite_benefit_lv1_rate', 0), 0, 100);
//        $lv2_rate = _between_(Settings::get('user_invite_benefit_lv2_rate', 0), 0, 100);
//        $lv3_rate = _between_(Settings::get('user_invite_benefit_lv3_rate', 0), 0, 100);


        $max_layer = Settings::get('user_invite_benefit_max_layer', 3);
        if($max_layer == 1){
            $lv2_rate = 0;
            $lv3_rate = 0;
        }else if($max_layer == 2){
            $lv3_rate = 0;
        }

        if($lv1_rate == 0 && $lv2_rate == 0 && $lv3_rate == 0){
            return;
        }

        try{
            DB::beginTransaction();

            if($order_id > 0){
                $user_id = (int)($order->user_id);
                if(_empty_($user_id)){
                    DB::rollBack();
                    return;
                }
                $first_inviter = WxUser::where('id', $user_id)->value('who');

                if($first_inviter > 0){
                    // 检验一层上级是否
                    $first_inviter_obj = WxUser::find($first_inviter);
                    if($first_inviter_obj){
                        if(!in_array($first_inviter_obj->user_state, [0, 3])){
                            $lv1_rate = 0;
                        }
//                        if($first_inviter_obj->invite_benefit_lv1 != -1 && $first_inviter_obj->invite_benefit_lv1 >= 0){
//                            $lv1_rate = _between_($first_inviter_obj->invite_benefit_lv1, 0, 100);
//                        }
                        if($first_inviter_obj->invite_benefit_layer == 2){
                            $lv1_rate = _between_($benefit_rate_2['lv1'], 0, 100);
                        }else if($first_inviter_obj->invite_benefit_layer == 3){
                            $lv1_rate = _between_($benefit_rate_3['lv1'], 0, 100);
                        }
                    }
                }


                $price = $order->order_pay_price;
                $first_inviter_price = round($price * ($lv1_rate / 100), 2);

                $is_need_save = false;
                $record = new WxUserInviteBenefitRecord();
                if($first_inviter){
                    $record->user_id = $user_id;
                    $record->order_id = $order->id;
                    $record->order_price = $price;

                    if($first_inviter_price >= 0.01){
                        $is_need_save = true;
                        UserUtils::update_user_financial($first_inviter, 15, $first_inviter_price, '您获得一笔来自团队成员「<a href="/pages/user/user?id='.$user_id.'">'.UserUtils::get_cached_user_name($user_id).'</a>」的邀请奖励');
                        $record->lv1_user = $first_inviter;
                        $record->lv1_benefit = $first_inviter_price;
                    }

                    $second_inviter = WxUser::where('id', $first_inviter)->value('who');
                    if($second_inviter){

                        if($second_inviter > 0){
                            // 检验一层上级是否
                            $second_inviter_obj = WxUser::find($second_inviter);
                            if($second_inviter_obj){
                                if(!in_array($second_inviter_obj->user_state, [0, 3])){
                                    $lv2_rate = 0;
                                }
//                                if($second_inviter_obj->invite_benefit_lv2 != -1 && $second_inviter_obj->invite_benefit_lv2 >= 0){
//                                    $lv2_rate = _between_($second_inviter_obj->invite_benefit_lv2, 0, 100);
//                                }

                                if($second_inviter_obj->invite_benefit_layer == 2){
                                    $lv2_rate = _between_($benefit_rate_2['lv2'], 0, 100);
                                }else if($second_inviter_obj->invite_benefit_layer == 3){
                                    $lv2_rate = _between_($benefit_rate_3['lv2'], 0, 100);
                                }

                            }
                        }
                        $second_inviter_price = round($price * ($lv2_rate / 100), 2);

                        if($second_inviter_price >= 0.01){
                            $is_need_save = true;
                            UserUtils::update_user_financial($second_inviter, 16, $second_inviter_price, '您获得一笔来自团队成员「<a href="/pages/user/user?id='.$user_id.'">'.UserUtils::get_cached_user_name($user_id).'</a>」的邀请奖励');
                            $record->lv2_user = $second_inviter;
                            $record->lv2_benefit = $second_inviter_price;
                        }

                        $third_inviter = WxUser::where('id', $second_inviter)->value('who');
                        if($third_inviter){

                            if($third_inviter > 0){
                                // 检验一层上级是否
                                $third_inviter_obj = WxUser::find($third_inviter);
                                if($third_inviter_obj){
                                    if(!in_array($third_inviter_obj->user_state, [0, 3])){
                                        $lv3_rate = 0;
                                    }
//                                    if($third_inviter_obj->invite_benefit_lv3 != -1 && $third_inviter_obj->invite_benefit_lv3 >= 0){
//                                        $lv3_rate = _between_($third_inviter_obj->invite_benefit_lv3, 0, 100);
//                                    }
                                    if($third_inviter_obj->invite_benefit_layer == 2){
                                        $lv3_rate = _between_($benefit_rate_2['lv3'], 0, 100);
                                    }else if($third_inviter_obj->invite_benefit_layer == 3){
                                        $lv3_rate = _between_($benefit_rate_3['lv3'], 0, 100);
                                    }
                                }
                            }
                            $third_inviter_price = round($price * ($lv3_rate / 100), 2);

                            if($third_inviter_price >= 0.01){
                                $is_need_save = true;
                                UserUtils::update_user_financial($third_inviter, 17, $third_inviter_price, '您获得一笔来自团队成员「<a href="/pages/user/user?id='.$user_id.'">'.UserUtils::get_cached_user_name($user_id).'</a>」的邀请奖励');
                                $record->lv3_user = $third_inviter;
                                $record->lv3_benefit = $third_inviter_price;
                            }
                        }
                    }

                }
                if($is_need_save){
                    $record->save();
                }
            }else if($shop_order_id > 0){
                $user_id = (int)($order->user_id);
                if(_empty_($user_id)){
                    DB::rollBack();
                    return;
                }

                // 去掉已经退款的
                $orderGoods_recharge = WxShopOrderGoods::where([
                    ['order_id', '=', $shop_order_id], ['state', '=', 0]
                ])->sum('recharge');


                $first_inviter = WxUser::where('id', $user_id)->value('who');
                if($first_inviter > 0){
                    // 检验一层上级是否
                    $first_inviter_obj = WxUser::find($first_inviter);
                    if($first_inviter_obj){
                        if(!in_array($first_inviter_obj->user_state, [0, 3])){
                            $lv1_rate = 0;
                        }
//                        if($first_inviter_obj->invite_benefit_lv1 != -1 && $first_inviter_obj->invite_benefit_lv1 >= 0){
//                            $lv1_rate = _between_($first_inviter_obj->invite_benefit_lv1, 0, 100);
//                        }
                        if($first_inviter_obj->invite_benefit_layer == 2){
                            $lv1_rate = _between_($benefit_rate_2['lv1'], 0, 100);
                        }else if($first_inviter_obj->invite_benefit_layer == 3){
                            $lv1_rate = _between_($benefit_rate_3['lv1'], 0, 100);
                        }
                    }
                }

                $first_inviter_price = round($orderGoods_recharge * ($lv1_rate / 100), 2);

                $record = new WxUserInviteBenefitRecord();
                $is_need_save = false;

                if($first_inviter){
                    $record->user_id = $user_id;
                    $record->shop_order_id = $order->id;
                    $record->order_price = $orderGoods_recharge;

                    if($first_inviter_price >= 0.01){
                        $is_need_save = true;
                        UserUtils::update_user_financial($first_inviter, 15, $first_inviter_price, '您获得一笔来自团队成员「<a href="/pages/user/user?id='.$user_id.'">'.UserUtils::get_cached_user_name($user_id).'</a>」的邀请奖励');
                        $record->lv1_user = $first_inviter;
                        $record->lv1_benefit = $first_inviter_price;
                    }


                    $second_inviter = WxUser::where('id', $first_inviter)->value('who');
                    if($second_inviter){

                        if($second_inviter > 0){
                            // 检验一层上级是否
                            $second_inviter_obj = WxUser::find($second_inviter);
                            if($second_inviter_obj){
                                if(!in_array($second_inviter_obj->user_state, [0, 3])){
                                    $lv2_rate = 0;
                                }
//                                if($second_inviter_obj->invite_benefit_lv2 != -1 && $second_inviter_obj->invite_benefit_lv2 >= 0){
//                                    $lv2_rate = _between_($second_inviter_obj->invite_benefit_lv2, 0, 100);
//                                }
                                if($second_inviter_obj->invite_benefit_layer == 2){
                                    $lv2_rate = _between_($benefit_rate_2['lv2'], 0, 100);
                                }else if($second_inviter_obj->invite_benefit_layer == 3){
                                    $lv2_rate = _between_($benefit_rate_3['lv2'], 0, 100);
                                }
                            }
                        }
                        $second_inviter_price = round($orderGoods_recharge * ($lv2_rate / 100), 2);

                        if($second_inviter_price >= 0.01){
                            $is_need_save = true;
                            UserUtils::update_user_financial($second_inviter, 16, $second_inviter_price, '您获得一笔来自团队成员「<a href="/pages/user/user?id='.$user_id.'">'.UserUtils::get_cached_user_name($user_id).'</a>」的邀请奖励');
                            $record->lv2_user = $second_inviter;
                            $record->lv2_benefit = $second_inviter_price;
                        }


                        $third_inviter = WxUser::where('id', $second_inviter)->value('who');
                        if($third_inviter){

                            if($third_inviter > 0){
                                // 检验一层上级是否
                                $third_inviter_obj = WxUser::find($third_inviter);
                                if($third_inviter_obj){
                                    if(!in_array($third_inviter_obj->user_state, [0, 3])){
                                        $lv3_rate = 0;
                                    }
//                                    if($third_inviter_obj->invite_benefit_lv3 != -1 && $third_inviter_obj->invite_benefit_lv3 >= 0){
//                                        $lv3_rate = _between_($third_inviter_obj->invite_benefit_lv3, 0, 100);
//                                    }
                                    if($third_inviter_obj->invite_benefit_layer == 2){
                                        $lv3_rate = _between_($benefit_rate_2['lv3'], 0, 100);
                                    }else if($third_inviter_obj->invite_benefit_layer == 3){
                                        $lv3_rate = _between_($benefit_rate_3['lv3'], 0, 100);
                                    }
                                }
                            }
                            $third_inviter_price = round($orderGoods_recharge * ($lv3_rate / 100), 2);

                            if($third_inviter_price >= 0.01) {
                                $is_need_save = true;
                                UserUtils::update_user_financial($third_inviter, 17, $third_inviter_price, '您获得一笔来自团队成员「<a href="/pages/user/user?id='.$user_id.'">'.UserUtils::get_cached_user_name($user_id).'</a>」的邀请奖励');
                                $record->lv3_user = $third_inviter;
                                $record->lv3_benefit = $third_inviter_price;
                            }

                        }
                    }

                }
                if($is_need_save){
                    $record->save();
                }
            }

            DB::commit();
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            DB::rollBack();
        }
    }

}
